package com.lungle.warmdiary.app.view.wallet.fragment;

import android.app.Activity;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.lungle.warmdiary.R;
import com.lungle.warmdiary.app.api.remote.ApiFactory;
import com.lungle.warmdiary.app.base.BaseListFragment;
import com.lungle.warmdiary.app.base.ListBaseAdapter;
import com.lungle.warmdiary.app.model.Result;
import com.lungle.warmdiary.app.model.response.TradeRecoder;
import com.lungle.warmdiary.app.model.response.TradeRecordList;
import com.lungle.warmdiary.app.ui.empty.EmptyLayout;
import com.lungle.warmdiary.app.utils.DateUtil;
import com.lungle.warmdiary.app.utils.ImageUtils;
import com.lungle.warmdiary.app.utils.SimpleAnimation;
import com.lungle.warmdiary.app.utils.TDevice;
import com.lungle.warmdiary.app.utils.UIHelper;
import com.lungle.warmdiary.app.view.wallet.adapter.TradeRecordAdapter;
import com.umeng.analytics.MobclickAgent;

import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import cn.qqtheme.framework.picker.OptionPicker;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * Created by God on 2016/8/8.
 */
public class TradeRecordFragment extends BaseListFragment<TradeRecoder> {
    private static final String TRADE_RECORD_SCREEN = "trade record screen";

    TextView mTvTradeType;
    TextView mTvTradeTime;
    private LinearLayout mLlHeader;
    private PopupWindow popup;
    private TypeSelector mTypeSelector;
    private TypeSelector mSelector;
    private volatile String mType;
    private Bitmap mSelectBitmap;
    private Bitmap mUnselectBitmap;
    private Resources mRes;
    private ImageView mIvTimeTip;
    private ImageView mIvTypeTip;
    private DateSelector mDateSelector;
    private List<Button> mButtons = new ArrayList<>();
    private String month = "";


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_pull_refresh_listview_header_tail;
    }


    @Override
    public void initView(View view) {
        super.initView(view);
        mLlHeader = (LinearLayout) view.findViewById(R.id.ll_header);
        mLlHeader.setVisibility(View.VISIBLE);
        View headerView = inflateView(R.layout.view_header_trade);
        mTvTradeTime = (TextView) headerView.findViewById(R.id.tv_trade_time);
        mTvTradeType = (TextView) headerView.findViewById(R.id.tv_trade_type);
        mIvTimeTip = (ImageView) headerView.findViewById(R.id.iv_trade_time_tip);
        mIvTypeTip = (ImageView) headerView.findViewById(R.id.iv_trade_type_tip);


        mRes = getApplication().getResources();
        mSelectBitmap = BitmapFactory.decodeResource(mRes, R.drawable.ic_under_arrow_selected);
        mUnselectBitmap = BitmapFactory.decodeResource(mRes, R.drawable.ic_under_arrow_unselected);

        mSelectBitmap = ImageUtils.zoomBitmap(mSelectBitmap, 15, 12);
        mUnselectBitmap = ImageUtils.zoomBitmap(mUnselectBitmap, 15, 12);


        mTvTradeType.setOnClickListener(this);
        mTvTradeTime.setOnClickListener(this);

        mLlHeader.addView(headerView, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

        initTypeSelector();
        initTimeSelector();

    }


    @Override
    public void onItemClick(AdapterView parent, View view, int position, long id) {
        TradeRecoder recoder = mAdapter.getItem(position);
        if (recoder != null)
            UIHelper.showTradeRecordDetail(getActivity(), recoder);
    }


    @Override
    public void initData() {

    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(TRADE_RECORD_SCREEN);
        MobclickAgent.onResume(getActivity());

    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(TRADE_RECORD_SCREEN);
        MobclickAgent.onPause(getActivity());

    }


    @Override
    protected void requestData(boolean refresh) {
        sendRequestData();
    }

    @Override
    protected void sendRequestData() {
        if (TextUtils.isEmpty(month)) {
            ApiFactory.getUserApi().getTradeRecord(mCurrentPage * getPageSize(), getPageSize(), mType, null).subscribeOn(Schedulers.io())
                    .compose(this.<Result<?>>bindToLifecycle())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(mSubscriber);
        } else if (TextUtils.isEmpty(mType)) {
            ApiFactory.getUserApi().getTradeRecord(mCurrentPage * getPageSize(), getPageSize(), null, month).subscribeOn(Schedulers.io())
                    .compose(this.<Result<?>>bindToLifecycle())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(mSubscriber);
        }


    }

    @Override
    protected ListBaseAdapter getListAdapter() {
        TradeRecordAdapter adapter = new TradeRecordAdapter();
        return adapter;
    }


    @Override
    protected TradeRecordList parseList(InputStream is) throws Exception {
        return TradeRecordList.parse(is);
    }

    @Override
    protected TradeRecordList readList(Serializable seri) {
        return (TradeRecordList) seri;
    }


    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_trade_type:
                SimpleAnimation.rotateArrow(mIvTypeTip, false);
                showTypeSelector(view);
                break;
            case R.id.tv_trade_time:
                SimpleAnimation.rotateArrow(mIvTimeTip, false);
                if (!mDateSelector.isShowing()) {
                    mDateSelector.show();
                } else {
                    mDateSelector.dismiss();
                }
                break;
        }
    }


    private void initTimeSelector() {
        String[] months = DateUtil.months();
        mDateSelector = new DateSelector(getActivity(), months);
        mDateSelector.setOnOptionPickListener(new OptionPicker.OnOptionPickListener() {
            @Override
            public void onOptionPicked(int position, String date) {
                searchByDate(date);
            }
        });
    }


    private void initTypeSelector() {
        if (popup == null) {
            View view = inflateView(R.layout.view_trade_type_select);
            Button btnIncomeActive = (Button) view.findViewById(R.id.btn_income_active);
            Button btnIncomeAll = (Button) view.findViewById(R.id.btn_income_all);
            Button btnIncomeReffer = (Button) view.findViewById(R.id.btn_income_reffer);
            Button btnTradeFail = (Button) view.findViewById(R.id.btn_trade_fail);

            mButtons.add(btnIncomeActive);
            mButtons.add(btnIncomeAll);
            mButtons.add(btnIncomeReffer);
            mButtons.add(btnTradeFail);


            popup = new PopupWindow(view, (int) TDevice.getScreenWidth(), (int) TDevice.getScreenHeight());
            mSelector = new TypeSelector(popup);

            btnIncomeActive.setOnClickListener(mSelector);
            btnIncomeAll.setOnClickListener(mSelector);
            btnIncomeReffer.setOnClickListener(mSelector);
            btnTradeFail.setOnClickListener(mSelector);

            Button btnExpendAll = (Button) view.findViewById(R.id.btn_expend_all);
            Button btnExpendTakecah = (Button) view.findViewById(R.id.btn_expend_takecash);
//            Button btnExpendTax = (Button) view.findViewById(R.id.btn_expend_tax);

            mButtons.add(btnExpendAll);
            mButtons.add(btnExpendTakecah);
//            mButtons.add(btnExpendTax);


            btnExpendAll.setOnClickListener(mSelector);
            btnExpendTakecah.setOnClickListener(mSelector);
//            btnExpendTax.setOnClickListener(mSelector);

            popup.setFocusable(true);
            popup.setOutsideTouchable(true);
            popup.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#f3122277")));
            popup.setOnDismissListener(() -> {
                SimpleAnimation.rotateArrow(mIvTypeTip, true);
            });
        }
    }


    private void restoreButtonState() {
        for (Button button : mButtons) {
            button.setTextColor(Color.BLACK);

        }
    }


    private void showTypeSelector(View v) {
        popup.showAsDropDown(v, 0, 5);
    }


    class TypeSelector implements View.OnClickListener {
        private String type = "";

        private PopupWindow mPopupWindow;

        public TypeSelector(PopupWindow popupWindow) {
            mPopupWindow = popupWindow;
        }

        @Override
        public void onClick(View v) {
            String tType = "";
            int id = v.getId();
            restoreButtonState();
            switch (id) {
                case R.id.btn_income_active:
                    ((Button) v).setTextColor(Color.parseColor("#f94848"));
                    tType = TradeRecoder.TYPE_CAMPAIGN_INCOME + "," + TradeRecoder.TYPE_CAMPAIGN_ACTIVE + "," + TradeRecoder.TYPE_CAMPAIGN_CONVERSION;
                    break;
                case R.id.btn_income_all:
                    ((Button) v).setTextColor(Color.parseColor("#f94848"));
                    tType = TradeRecoder.TYPE_WITHDRAW_RETURN + "," + TradeRecoder.TYPE_CAMPAIGN_INCOME + "," + TradeRecoder.TYPE_INVITE_USRE_AWARD + "," + TradeRecoder.TYPE_CAMPAIGN_ACTIVE + "," + TradeRecoder.TYPE_CAMPAIGN_CONVERSION;
                    break;
                case R.id.btn_income_reffer:
                    ((Button) v).setTextColor(Color.parseColor("#f94848"));
                    tType = TradeRecoder.TYPE_INVITE_USRE_AWARD + "";
                    break;
                case R.id.btn_trade_fail:
                    ((Button) v).setTextColor(Color.parseColor("#f94848"));
                    tType = TradeRecoder.TYPE_WITHDRAW_RETURN + "";
                    break;
                case R.id.btn_expend_all://全部支出
                    ((Button) v).setTextColor(Color.parseColor("#f94848"));
                    tType = "" + TradeRecoder.TYPE_WITHDRAW;
                    break;
                case R.id.btn_expend_takecash://提现
                    ((Button) v).setTextColor(Color.parseColor("#f94848"));
                    tType = TradeRecoder.TYPE_WITHDRAW + "";
                    break;
//                case R.id.btn_expend_tax://扣税
//                    ((Button) v).setTextColor(Color.parseColor("#f94848"));
//                    tType = TradeRecoder.TYPE_TAX + "";
//                    break;
            }

            searchByType(tType);
            mPopupWindow.dismiss();
        }

    }


    private void searchByDate(String date) {
        date = date.replaceAll("年", "").replaceAll("月", "");
        month = date;
        mType = "";
        mErrorLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
        sendRequestData();
    }

    private void searchByType(String type) {
        mType = type;
        month = "";
        mErrorLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
        sendRequestData();
    }

    class DateSelector extends OptionPicker {


        public DateSelector(Activity activity, String[] options) {
            super(activity, options);
            setSelectedIndex(0);
        }

        @Override
        public void show() {
            super.show();

        }

        @Override
        public void dismiss() {
            super.dismiss();
        }
    }

}
